package com.think.archive.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.think.archive.common.BaiduToken;
import com.think.archive.service.OcrService;
import com.think.archive.util.HttpClientUtil;
import com.think.archive.util.baidu.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class OcrServiceImpl implements OcrService {

    @Value("${baiduApp.APIKey}")
    private String apiKey;
    @Value("${baiduApp.SecretKey}")
    private String secretKey;


    @Override
    public void getToken() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("grant_type","client_credentials");
        map.put("client_id",apiKey);
        map.put("client_secret",secretKey);
        JSONObject jsonObject= JSON.parseObject(HttpClientUtil.post("https://aip.baidubce.com/oauth/2.0/token",map));
        BaiduToken.refreshToken=jsonObject.getString("refresh_token");
        BaiduToken.expiresIn=jsonObject.getString("expires_in");
        BaiduToken.sessionKey=jsonObject.getString("session_key");
        BaiduToken.accessToken=jsonObject.getString("access_token");
        BaiduToken.scope=jsonObject.getString("scope");
        BaiduToken.sessionSecret=jsonObject.getString("session_secret");
    }

    @Override
    public String recognise(String image, String templateSign, int classifierId) throws Exception {
        if(BaiduToken.accessToken==null){
            getToken();
        }
        String recogniseParams = "templateSign="+templateSign+"&image=" + image;
        String result = HttpUtil.post("https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise",
                BaiduToken.accessToken,
                recogniseParams);
        return result;

    }
}
